package com.manager.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Random;

/**
 * 邮箱发送工具类
 *
 * @author zhou
 * @date 2021/07/10 23:12
 **/
@Component
public class SendMailUtils {

  /**
   * 发件对象
   */
  @Resource
  private JavaMailSender javaMailSender;

  /**
   * 发件人
   */
  @Value("${spring.mail.username}")
  private String username;

  /**
   * 发送邮件
   *
   * @param title   标题
   * @param content 邮件内容
   * @param email   接收者的邮箱
   */
  public void sendNormalEmail(String title, String content, String email) {
    try {
      String dName = "Doc Manager平台";
      // 创建复杂邮箱对象
      MimeMessage mimeMessage = javaMailSender.createMimeMessage();
      // 组装复杂邮箱对象
      MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
      helper.setSubject(title);
      helper.setText(content, true);
      helper.setFrom(username, dName);
      helper.setTo(email);
      // 发送
      javaMailSender.send(mimeMessage);
    } catch (MessagingException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
  }

  /**
   * 随机生成6位数的验证码
   *
   * @return String code
   */
  public String randomCode() {
    StringBuilder str = new StringBuilder();
    Random random = new Random();
    for (int i = 0; i < 6; i++) {
      str.append(random.nextInt(10));
    }
    return str.toString();
  }
}
